package com.example.goodpet.community.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.StaggeredGridLayoutHelper;
import com.example.goodpet.R;
import com.example.goodpet.activity.SearchActivity;
import com.example.goodpet.activity.TieziInfoActivity;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.common.LoadingPage;
import com.example.goodpet.community.activity.ReleaseTieziActivity;
import com.example.goodpet.community.adapter.CommunityRecyclerViewAdapter;
import com.example.goodpet.community.bean.UserTieziInfo;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.home.homeRecommend.adapter.RecommendRecycleViewAdapter;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.UIUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CommunityContent extends BaseFragment {

    private RecyclerView rv_community;
    private CommunityRecyclerViewAdapter adapter;
    private LoadMoreWrapper loadMoreWrapper;
    private LinearLayout pageError;
    private String TAG = this.getClass().getSimpleName();

    private Retrofit retrofit;
    private HomeService homeService;

    private static List<UserTieziInfo> userTieziInfos = new ArrayList<>();

    private long seed= TimeSeed.Get();
    //VLayout
    private VirtualLayoutManager layoutManager;
    //主页上方适配器集合
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();
    //用来获取布局
    private LayoutInflater mLayoutInflater;
    private LoadingPage view;
    @Override
    public View initView() {
        view=new LoadingPage(requireActivity()) {
            @Override
            public int getLayoutXmlId() {
                return R.layout.fragment_home_focus;
            }
        };
        //View view = View.inflate(mContext, R.layout.fragment_community, null);


        rv_community = view.findViewById(R.id.recyclerView);
        pageError=view.findViewById(R.id.page_error);
        //初始化监听
        initListener();

        return view;
    }

    @Override
    public void initData() {
        view.setStateCurrent(LoadingPage.STATE_loading);
        retrofit= RetrofitSingleton.getRetrofitConstance();
        homeService=retrofit.create(HomeService.class);
        homeService.selectAllUserTieziInfo(seed, MyApplication.user.getId(),1)
                .enqueue(new Callback<ResponseBody<List<UserTieziInfo>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<UserTieziInfo>>> call, Response<ResponseBody<List<UserTieziInfo>>> response) {
                        ResponseBody<List<UserTieziInfo>> body = response.body();
                        if(body.getCode()==200){
                            view.setStateCurrent(LoadingPage.STATE_SUCCESS);
//                            Log.e(TAG, "onResponse: "+body.getData().get(0) );
                            userTieziInfos=body.getData();
                        }else if(body.getCode()==404){
                            view.setStateCurrent(LoadingPage.STATE_EMPTY);
                            userTieziInfos=null;
                            //UIUtils.toast("未获取到社区信息",false);
                        }
                        //获取数据成功后初始化显示宠物信息的recyclerview
                        initVLayoutRvTiezi();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<UserTieziInfo>>> call, Throwable t) {
                        //UIUtils.toast("网络通信失败",false);
                        view.setStateCurrent(LoadingPage.STATE_ERROR);
                    }
                });
    }

    private void initVLayoutRvTiezi() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rv_community.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rv_community.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        addTieziAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdapters);
        rv_community.setAdapter(mainAdapter);
    }

    private void addTieziAdapter() {
        GridLayoutHelper helper = new GridLayoutHelper(2);

        adapter = new CommunityRecyclerViewAdapter(mContext, userTieziInfos,getActivity());
        loadMoreWrapper = new LoadMoreWrapper(adapter){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return helper;
            }
        };
//        rvParent.setAdapter(loadMoreWrapper);
        subAdapters.add(loadMoreWrapper);


        rv_community.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                homeService.selectAllUserTieziInfo(seed,MyApplication.user.getId(),++loadMoreWrapper.page)
                        .enqueue(new Callback<ResponseBody<List<UserTieziInfo>>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<List<UserTieziInfo>>> call, Response<ResponseBody<List<UserTieziInfo>>> response) {
                                ResponseBody<List<UserTieziInfo>> body = response.body();
                                if(body.getCode()==200){
                                    List<UserTieziInfo> data = body.getData();
//                                   Log.e(TAG, "onResponse: "+data);
                                    userTieziInfos.addAll(data);
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                                }else if (body.getCode()==404){
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                               }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<List<UserTieziInfo>>> call, Throwable t) {
                                Log.e(TAG, "onFailure: "+t.getMessage());
                                UIUtils.toast("连接服务器失败",false);
                            }
                        });
            }
        });

    }

    private void initListener() {
        pageError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

    }

    @SuppressLint("NotifyDataSetChanged")
    public void refresh(int position, UserTieziInfo info){

        UserTieziInfo userTieziInfo = userTieziInfos.get(position);
        long userId = userTieziInfo.getUserId();
        for (UserTieziInfo tieziInfo : userTieziInfos) {
            if(tieziInfo.getUserId()==userId) tieziInfo.setFoucs(info.isFoucs());
        }
        userTieziInfo.setLike(info.isLike());
        userTieziInfo.setLikeNum(info.getLikeNum());
        userTieziInfo.setCollect(info.isCollect());
        userTieziInfo.setCollectNum(info.getCollectNum());
        userTieziInfo.setMessageNum(info.getMessageNum());
        userTieziInfo.setFoucs(info.isFoucs());
        loadMoreWrapper.notifyDataSetChanged();
//        adapter.notifyDataSetChanged();

    };
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
